<template>
    <div>
        <t-header></t-header>
        <div class="t-bg">
            <img src="../../assets/images/my.jpg" alt="">
        </div>
        <!-- 用户信息 -->
        <div class="user-info">
            <div class="w">
                <!-- 头像 -->
                <div class="avatar">
                    <input @change="uploadAvatar($event)" title="修改头像" class="avatar-file" type="file">
                    <img :src="avatar == 'no' ? 'http://47.105.157.158:3000/images/upload/default.jpg' : `http://47.105.157.158:3000/images/upload/${avatar}`" alt="">
                    <div class="mask">
                        <span>编辑头像</span>
                    </div>
                </div>
                <!-- 用户名 -->
                <div class="user-name" v-if="userInfo != null">
                    <span>{{userInfo.userName}}</span>
                </div>
                <!-- 用户关注等信息 -->
                <div class="user-fansh" v-if="userInfo != null">
                    <ul>
                        <li>
                            <div>{{userInfo.fansh.length}}</div>
                            <div>粉丝</div>
                        </li>
                        <li>
                            <div>{{userInfo.guanzhu.length}}</div>
                            <div>关注</div>
                        </li>
                        <li>
                            <div>{{userInfo.beizan}}</div>
                            <div>被赞</div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
         <!-- 查看作品 -->
         <div class="look">
             <div class="w">
                 <div class="lookall">图片作品<span>{{publishUser.length}}</span></div>
             </div>
         </div>
         <el-alert
            v-if="publishUser.length != 0"
            title="暂时不支持删除作品，请谅解（资源缺乏~~）"
            type="error"
            center
            show-icon>
        </el-alert>
         <!-- 作品展示 -->
         <div class="look-show">
             <div class="w">
                 <span v-if="publishUser.length == 0">你还没有发过作品哦</span>
                 <div v-else class="img-list">
                    <div class="list-item" :key="index" v-for="(item, index) in publishUser">
                        <img v-lazy="`http://47.105.157.158:3000/images/cat/${item.cat}/${item.pathName}`">
                    </div>
                 </div>
             </div>
         </div>
    </div>
</template>

<script>
import { Message } from 'element-ui';
import Header from '../../components/global/Header';
import Footer from '../../components/global/Footer';
import { ref, onMounted } from '@vue/composition-api';
import jquery from 'jquery';
import axios from 'axios';
export default {
    components: {
        't-header': Header,
        't-footer': Footer
    },
    setup(props, context) {

        // 配置axios
        axios.defaults.baseURL = 'http://47.105.157.158:3000';

        onMounted(() => {
            reloadIsLogin();
        })


        // 用户的发布作品
        const publishUser = ref('');
        // 获取用户的发布作品
        const getUserPublish = async function () {
            let { data: res } = await axios.get(`/user/imgs/${userInfo.value.email}`);
            if (res.status != 200)
                return context.parent.$message.error('获取用户的发布作品失败，请刷新后重试');
            publishUser.value = res.imgs;
        }
        
        // 刷新后，重新获取用户信息，避免刷新后共享数据丢失的BUG
        const reloadIsLogin = async function () {
            // 不在登录状态，就不发请求获取
            if (!window.localStorage.getItem('token'))
              return false;

            // 发送请求获取用户信息
            let token = window.localStorage.getItem('token');
            let { data: res } = await axios.get(`/user/login/${token}`);
            if (res.status != 200)
              return context.parent.$message.error('获取用户信息失败，请重新登录');

            // 重新设置数据给store共享
            context.parent.$store.commit('setIsLogin', true);
            context.parent.$store.commit('setUser', res.user);
            context.parent.$store.commit('setToken', token);
            avatar.value = res.user.avatar;
            userInfo.value = res.user;
            context.parent.$nextTick(() => {
                getUserPublish();
            })
        }
        // 用户信息
        const userInfo = ref(context.parent.$store.state.user || null);
        // 用户头像
        const avatar = ref(context.parent.$store.state.user.avatar || 'no');
        // 上传头像
        const uploadAvatar = function (event) {
            let formData = new FormData();
            formData.append('avatar', event.target.files[0]);
            formData.append('user', context.parent.$store.state.user.email);
            jquery.ajax({
                type: 'post',
                url: 'http://47.105.157.158:3000/upload/avatar',
                contentType: false,
                processData: false,
                data: formData,
                success: function(response) {
                    if (response.status != 200) {
                        context.parent.$message.error('上传头像失败，请重新尝试');
                    } else {
                        context.parent.$message.success('上传头像成功');
                        avatar.value = response.avatar;
                    }
                }
            });
        }

        const methods = { uploadAvatar }

        return {
            ...methods,
            avatar,
            userInfo,
            publishUser
        }
    },
    beforeRouteEnter (to, from, next) {
        // 没有登录进行拦截
        if (!window.localStorage.getItem('token')) {
            let that = this;
            Message.error('您还没有登录，不能使用该功能');
            setTimeout(() => {
                next('/home');
            }, 2000);
        } else {
            next();
        }
    },

}
</script>

<style lang="less" scoped>
.t-bg {
    height: 360px;
    img {
        width: 100%;
        height: 100%;
    }
}

.avatar {
    position: absolute;
    top: -66px;
    left: 0;
    width: 140px;
    height: 140px;
    &:hover .mask {
        opacity: 1;
    }
    .avatar-file {
        width: 140px;
        height: 140px;
        background: red;
        border-radius: 50%;
        // opacity: 0;
        outline: none;
        cursor: pointer;
    }
    img {
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        border-radius: 50%;
        pointer-events: none;
    }
    .mask {
        opacity: 0;
        border-radius: 50%;
        transition: all .6s;
        text-align: center;
        span {
            line-height: 140px;
            color: #fff;
            font-weight: 700;
        }
    }
}

.user-name {
    position: absolute;
    left: 170px;
    top: -46px;
    font-size: 22px;
    color: #fff;
    letter-spacing: 2px;
}

.user-fansh {
    position: absolute;
    left: 150px;
    top: 8px;
    li {
        float: left;
        text-align: center;
        margin: 0 12px;
        div:nth-child(1) {
            color: #4b4b4b;
            font-weight: 700;
            cursor: pointer;
        }
        div:nth-child(2) {
            color: #838385;
            font-size: 14px;
        }
    }
}

.look {
    margin-top: 100px;
    height: 60px;
    border: 1px solid #c9ece0;
    line-height: 60px;
    border-left: none;
    border-right: none;
    padding-left: 10px;
    .lookall {
        font-size: 16px;
        font-weight: 700;
        color: #4b4b4b;
        letter-spacing: 2px;
        span {
            margin-left: 10px;
        }
    }
}

.look-show {
    margin-top: 32px;
    text-align: center;
    font-size: 26px;
    font-weight: 700;
    color: #b5b5b5;
}

.img-list {
    columns: auto 3;
    column-gap: 8px;
    break-inside: avoid;
    .list-item {
        img {
            width: 100%;
        }
    }

}
</style>